<template>
  <div>
    <el-button 
      type="primary" 
      icon="el-icon-arrow-left"
      @click="$router.push('/admin/category')"
      style="margin-bottom: 20px">
      返回
    </el-button>
    <el-form style="width: 60%" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="分类ID">
        <el-input v-model="ruleForm.bookcaseid" readOnly></el-input>
      </el-form-item>
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="ruleForm.categoryName"></el-input>
      </el-form-item>
      <el-form-item label="分类描述" prop="description">
        <el-input type="textarea" v-model="ruleForm.description"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        bookcaseid: '',
        categoryName: '',
        description: ''
      },
      rules: {
        categoryName: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '分类描述不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      const _this = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.put('http://localhost:8181/bookCategory/update', this.ruleForm).then(function(resp) {
            if (resp.data == 'success') {
              _this.$alert('分类信息修改成功！', '消息', {
                confirmButtonText: '确定',
                callback: action => {
                  _this.$router.push('/admin/category');
                }
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  created() {
    const _this = this;
    console.log('正在加载分类ID:', this.$route.query.bookcaseid);
    axios.get('http://localhost:8181/bookCategory/findById/' + this.$route.query.bookcaseid)
      .then(function(resp) {
        console.log('获取到分类数据:', resp.data);
        if (resp.data) {
          _this.ruleForm = resp.data;
        } else {
          console.error('无效的分类数据:', resp.data);
          _this.$message.error('获取分类信息失败');
          _this.$router.push('/admin/category');
        }
      })
      .catch(error => {
        console.error('获取分类信息出错:', error);
        _this.$message.error('获取分类信息出错');
        _this.$router.push('/admin/category');
      });
  }
};
</script>
